package com.ffyc.cemp.web.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.ffyc.cemp.common.dto.HttpResult;
import com.ffyc.cemp.common.exception.user.VCodeErrorException;
import com.ffyc.cemp.common.exception.user.VCodeExpiredException;
import com.ffyc.cemp.domain.entity.User;
import com.ffyc.cemp.services.service.IUserService;
import com.ffyc.cemp.tools.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户api接口")
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService ius;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation(value = "registry", notes = "用户注册")
    @PostMapping("/registry")
    public HttpResult registry(@RequestBody User user) {
        ius.registry(user);
        return HttpResult.success("用户:" + user.getUsername() + "注册成功");
    }


    @ApiOperation(value = "login", notes = "用户登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "username", required = true),
            @ApiImplicitParam(name = "password", required = true)})
    @GetMapping("/login")
    public HttpResult login(String username, String password) {
        User user = ius.login(username, password);
        //登录成功
        //1.产生token
        String token = JwtUtils.getInstance().build(
                new HashMap<String, Object>() {{
                    put("username", user.getUsername());
                    put("role", user.getRole());
                }}, 60, user.getSign());


        //2. 放入redis
        redisTemplate.opsForValue().set(token, user);
        redisTemplate.expire(token, 60 * 3, TimeUnit.SECONDS);


        log.debug("用户登录成功，产生token:{}", token);
        return HttpResult.success(token);
    }

    @ApiOperation(value = "logout", notes = "用户退出登录")
    @GetMapping("/logout")
    public HttpResult logout(HttpServletRequest request) {


        String token = request.getHeader("myToken");
        redisTemplate.delete(token);
        log.debug("redis销毁token:{}完成", token);
        return HttpResult.success("用户退出成功");
    }


    @ApiOperation(value = "buildVCode", notes = "生成验证码")
    @GetMapping("/buildVCode")
    public HttpResult<String[]>buildVCode(){
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
        // 重新生成code
        lineCaptcha.createCode();

        String vCode=lineCaptcha.getCode();

        //1.生成雪花id
        //2. 存储code到redis中
        //3. 返回前端

        //简单使用
        //long id = IdUtil.getSnowflakeNextId();
        String id = IdUtil.getSnowflakeNextIdStr();
        stringRedisTemplate.opsForValue().set(id,vCode);

        String vImage=lineCaptcha.getImageBase64Data();

        return HttpResult.success(new String[]{vCode, vImage});
    }


    public HttpResult<User>customerLogin(String username,String password,String vCode,String codeId){
        String code=stringRedisTemplate.opsForValue().get(codeId);
        if(code==null){
            throw new VCodeExpiredException("验证码过期异常");
        }
        if(!code.equals(vCode)){
            throw new VCodeErrorException("验证码错误异常");
        }
        User user=ius.login(username,password);

        return HttpResult.success(user);
    }



}
